package com.starblink.search.search.ui.cell

import android.graphics.drawable.RotateDrawable
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.setPadding
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.RecyclerView
import com.google.android.flexbox.FlexboxLayoutManager
import com.starblink.android.basic.adapter.BaseBindingVH
import com.starblink.android.basic.adapter.BaseVH
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.basic.ext.screenWidth
import com.starblink.library.widget.databinding.CellSearchHistoryBinding
import com.starblink.library.widget.databinding.CellSearchHistoryExpandBinding

/**
 * 包含自己折叠功能
 */
class HistoryAdapter(parent: RecyclerView, val data: List<String>, private val onItemClick: ((model: String) -> Unit)? = null) :
    MutableAdapter(data) {

    private var expanded = false

    private var overOneLine = false

    private val emptyBindingForMeasure = CellSearchHistoryBinding.inflate(parent.inflater, parent, false)

    init {
        addVhDelegate { it ->
            SearchHistoryCell(CellSearchHistoryBinding.inflate(it.inflater, it, false)) {
                onItemClick?.invoke(it)
            }
        }
    }

    override fun getItemViewType(position: Int): Int {
        if (overOneLine && position == itemCount - 1) {
            return TYPE_EXPAND
        }
        return super.getItemViewType(position)
    }

    override fun onCreateVH(parent: ViewGroup, viewType: Int, flag: Int): BaseVH<out Any?> {
        if (viewType == TYPE_EXPAND) {
            return ExpandCell(CellSearchHistoryExpandBinding.inflate(parent.inflater, parent, false)) {
                expanded = it
                notifyItemRangeChanged(0, itemCount)
            }
        }
        return super.onCreateVH(parent, viewType, flag)
    }

    override fun onBindViewHolder(holder: BaseVH<*>, position: Int) {
        if (overOneLine && position == itemCount - 1) {
            (holder as ExpandCell?)?.onBind(expanded, position)
        } else {
            super.onBindViewHolder(holder, position)
        }

    }

    override fun getItemCount(): Int {
        var dataCount = super.getItemCount()
        var textW = 0f
        var index = 0
        val limitW = screenWidth - 32.dp2px()
        val gap = 8.dp2px()
        var expandRecentIndex = 0
        overOneLine = false
        val expandWidgetWidth = 38.dp2px()
        while(index < data.size) {
            val txtW = emptyBindingForMeasure.btn.paint.measureText(data[index])
            textW += txtW + gap + emptyBindingForMeasure.btn.run {
                paddingLeft + paddingRight
            }
            if (limitW - textW > 0 && limitW - textW < gap + expandWidgetWidth) {
                expandRecentIndex = index
            }
            if (textW > limitW) {
                overOneLine = true
                break
            }
            index ++
        }
        if (!expanded) {
            dataCount = if(overOneLine && index == 0) 1 else index
            if (overOneLine && index > 1 && textW + gap + expandWidgetWidth > limitW && expandRecentIndex > 0) {
                dataCount = expandRecentIndex
            }
        }

        return if (overOneLine) dataCount + 1 else dataCount
    }

    companion object {

        private const val TYPE_EXPAND = Int.MIN_VALUE

    }


}


class SearchHistoryCell(
    binding: CellSearchHistoryBinding,
    private val onClick: ((model: String) -> Unit)? = null
) : BaseBindingVH<String, CellSearchHistoryBinding>(binding) {

    init {
        itemView.updateLayoutParams<FlexboxLayoutManager.LayoutParams> {
//            alignSelf = AlignSelf.FLEX_START
        }
    }

    override fun onBind(model: String, position: Int) {
        binding.btn.text = model

        // 埋点：点击Recently Viewed列表Item
        binding.btn.trackData(
            element = SpmElementDef.SearchHistoryItemClick,
            page = SpmPageDef.SearchRecommendBody,
            onlyHit=true,
            params = mutableMapOf(
                "searchTerm" to model,
            )
        )

        binding.btn.setOnClickListener {
            onClick?.invoke(model)
        }
    }

}



private class ExpandCell(
    binding: CellSearchHistoryExpandBinding,
    private val onClick: ((model: Boolean) -> Unit)? = null
) : BaseBindingVH<Boolean, CellSearchHistoryExpandBinding>(binding) {

    init {
        binding.btn.let {
            RotateDrawable().drawable = ContextCompat.getDrawable(itemView.context, com.starblink.library.widget.R.mipmap.ic_his_arrow_down)
            it.setPadding(0)
            it.setImageDrawable(RotateDrawable().apply {
                drawable = ContextCompat.getDrawable(itemView.context, com.starblink.library.widget.R.mipmap.ic_his_arrow_down)
                fromDegrees = 0f
            })
        }
    }

    override fun onBind(expand: Boolean, position: Int) {
        (binding.btn.drawable as? RotateDrawable)?.let {
            it.level = if(!expand) 0 else 10000 / 2
            binding.btn.setImageDrawable(it)
        }
        binding.btn.setOnClickListener {
            onClick?.invoke(!expand)
        }
    }

}